import LinkedList from './链表.js'
import DoublyNode from './doublyNode.js'
class DoublyLinkedList extends LinkedList {
	constructor(element) {
		super(element)
		this.tail = undefined
	}
	push (element) {
		let doublyNode = new DoublyNode(element)
		if (this.count === 0) {
			this.head = doublyNode
			this.tail = doublyNode
		} else {
			this.tail.next = doublyNode
			doublyNode.prev = this.tail
			this.tail = doublyNode
		}
		this.count++
		return this
	}
	insert (element, index) {
		if (index >= 0 && index <= this.count) {
			let doublyNode = new DoublyNode(element)
			if (index === 0) {
				if (this.count === 0) {
					this.head = doublyNode
					this.tail = doublyNode
				} else {
					doublyNode.next = this.head
					this.head.prev = doublyNode
					this.head = doublyNode
				}
			} else if (index === this.count) {
				this.tail.next = doublyNode
				doublyNode.prev = this.tail
				this.tail = doublyNode
			} else {
				// 中间部分插入
				let prev = this.getElementAt(index - 1)
				let current = this.getElementAt(index)
				prev.next = doublyNode
				doublyNode.prev = prev
				doublyNode.next = current
				current.prev = doublyNode
			}
			this.count++
		}
	}
	removeAt (index) {
		if (index >= 0 && index < this.count) {
			if (index === 0) {
				this.head = this.head.next
				if (this.count === 1) {
					this.tail = null
				} else {
					this.head.prev = null
				}
			} else if (index === this.count - 1) {
				this.tail = this.tail.prev
				this.tail.next = null
			}else {
				let current = this.getElementAt(index)
				current.prev.next = current.next
				current.next.prev = current.prev
			}
			this.count--
		}
	}
}
let doublyLinkedList = new DoublyLinkedList()
doublyLinkedList.push('html').push('css').push('javascript')
doublyLinkedList.insert('vue',0)
// doublyLinkedList.removeAt(1)
console.log(doublyLinkedList)